import logging

from django import http
from django.core.cache import cache
from django.shortcuts import render

# Create your views here.
from django.views import View

from areas.models import Area
from meiduo_mall.utils.response_code import RETCODE



logger=logging.getLogger('django')
class AreasView(View):
    def get(self,request):
        area_id=request.GET.get('area_id')
        if  not area_id:
            # 查询省级数据
            province_list=cache.get('province_list')
            if not province_list:
                # Area.objects.filter(属性名__条件表达式=值)
                province_model_list=Area.objects.filter(parent__isnull=True)
                #将模型列表转换成字典列表
                try:
                    province_list=[]
                    for province_model in province_model_list:
                        province_dict={
                            'id':province_model.id,
                            'name':province_model.name
                        }
                        province_list.append(province_dict)
                    # 将省级数据进行缓存
                    cache.set('province_list',province_list,3600) # 1h
                    #响应省级JSON数据
                    return http.JsonResponse({'code':RETCODE.OK ,'errmsg':'ok','province_list':province_list})
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg':'省份查询错误'})
            else:
                return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'province_list': province_list})
        else:
            sub_data = cache.get('sub_area' + area_id)
            if not sub_data:
                try:
                    # 查询市区数据
                    parent_model=Area.objects.get(id=area_id)
                    # sub_model_list = parent_model.area_set.all()
                    sub_model_list=parent_model.subs.all()
                    subs=[]
                    for sub_model in sub_model_list:
                        sub_dict={
                           'id':sub_model.id,
                           'name':sub_model.name
                        }
                        subs.append(sub_dict)
                    sub_data={
                        'id':parent_model.id,
                        'name':parent_model.name,
                        'subs':subs
                    }
                    # 缓存市区数据
                    cache.set('sub_area'+area_id,sub_data,3600)
                    return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'sub_data': sub_data})
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '市区查询错误'})
            else:
                return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'sub_data': sub_data})
